package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    private CategoryService service;


    //新增分类
    @PostMapping
    public R saveCategory(@RequestBody Category category,HttpSession session){
      /*  Employee employee = (Employee) session.getAttribute("employee");
        category.setCreateTime(LocalDateTime.now());
        category.setUpdateTime(LocalDateTime.now());
        category.setCreateUser(employee.getId());
        category.setUpdateUser(employee.getId());*/

        service.save(category);
        return R.success(null);
    }
    //分页查询分类
    @GetMapping("/page")
    public R pageQuery(int page,int pageSize){

        //进行分页查询
        IPage<Category> iPage = new Page<>(page,pageSize);
        LambdaQueryWrapper<Category> qw = new LambdaQueryWrapper<>();
        qw.orderByAsc(Category::getSort);
        service.page(iPage,qw);
        long total = iPage.getTotal();
        List<Category> records = iPage.getRecords();
        Map map = new HashMap();
        map.put("total",total);
        map.put("records",records);
        return R.success(map);
    }
    //删除分类
    @DeleteMapping
    public R deleteCategory(Long id){

        service.deleteCategory(id);
        return R.success("删除成功");
    }
    @PutMapping
    public R updateCategory(@RequestBody Category category){

        service.updateById(category);
        return R.success("更新成功");

    }

    //根据条件查询分类表中所有的菜品分类（type=1）和所有的套餐分类（type=2）
    @GetMapping("/list")
    public R<List<Category>> list(Category category){


        LambdaQueryWrapper<Category> lqw = new LambdaQueryWrapper<>();
        lqw.eq(category.getType() != null, Category::getType,category.getType());
        lqw.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);
        List<Category> list = service.list(lqw);
        return R.success(list);
    }

}
